package org.shiro.demo.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.shiro.demo.dao.util.Pagination;
import org.shiro.demo.dao.util.QueryCondition;
import org.shiro.demo.entity.Administrator;
import org.shiro.demo.entity.ResponseResult;
import org.shiro.demo.entity.Role;
import org.shiro.demo.service.IAdminService;
import org.shiro.demo.service.IRoleService;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/admin")
public class AdminController {

	@Resource
	private IAdminService adminService;

	@Resource
	private IRoleService roleService;

	@RequestMapping(value = "/findAdmins")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("super-administrator")
	public Pagination<Administrator> findAdmins(@RequestParam("pageSize") Integer pageSize, //
			@RequestParam("pageNumber") Integer pageNumber,//
			@RequestParam("orderBy") String orderBy,//
			@RequestParam("asc") Boolean asc) {

		// List<QueryCondition> queryConditions = new
		// ArrayList<QueryCondition>();
		Pagination<Administrator> pagination = null;
		if (orderBy != null && asc != null) {
			pagination = adminService.getPagination(Administrator.class, null, " order by o." + orderBy + " " + (asc ? " ASC " : " DESC "), pageNumber, pageSize);
		} else {
			pagination = adminService.getPagination(Administrator.class, null, null, pageNumber, pageSize);
		}
		return pagination;
	}

	@RequestMapping(value = "/deleteById")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("super-administrator")
	public Object deleteById(int id) {
		ResponseResult rr = new ResponseResult();

		Administrator administrator = adminService.getById(Administrator.class, id);

		if (administrator == null) {
			rr.setCode(0);
			rr.setInfo("不存在该管理员");
			return rr;
		}

		try {
			adminService.delete(Administrator.class, id);
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			rr.setInfo("无权操作");
			return rr;
		}

		rr.setCode(1);
		rr.setInfo("success");
		return rr;
	}

	@RequestMapping(value = "/getRoles")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("super-administrator")
	public Object getRoles() {

		ResponseResult rr = new ResponseResult();
		List<Role> roles = new ArrayList<Role>();
		try {
			roles = roleService.getAll(Role.class);
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}
		rr.setObject(roles);
		rr.setCode(1);
		rr.setInfo("success");
		return rr;
	}

	@RequestMapping(value = "/getRolesById")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("super-administrator")
	public Object getRolesById(@RequestParam("id") int id) {

		return adminService.getById(Administrator.class, id).getRoles();
	}

	@RequestMapping(value = "/setRoles")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("super-administrator")
	public Object setRolesByIds(int id, Long[] ids) {
		ResponseResult rr = new ResponseResult();

		Administrator persist = adminService.getById(Administrator.class, id);
		List<Role> roles = adminService.getByIds(Role.class, ids);
		persist.setRoles(roles);
		try {
			adminService.update(persist);
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}
		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(null);

		return rr;
	}

	/***
	 * 
	 */
	@RequestMapping(value = "/updateInfo")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("super-administrator")
	public Object updateInfo(HttpServletRequest request, @RequestBody Administrator administrator) {
		ResponseResult rr = new ResponseResult();

		Administrator oAdministrator = adminService.getById(Administrator.class, administrator.getId());

		if (oAdministrator == null) {
			rr.setCode(0);
			rr.setInfo("不存在该管理员");
			return rr;
		}

		Administrator persistent = adminService.getById(Administrator.class, administrator.getId());
		// System.out.println(administrator);
		// set new property
		persistent.setName(administrator.getName());
		persistent.setSex(administrator.getSex());
		// persistent.setBirthday(administrator.getBirthday());
		persistent.setJob(administrator.getJob());
		persistent.setImage(administrator.getImage());
		persistent.setPhone(administrator.getPhone());
		persistent.setIncome(administrator.getIncome());
		persistent.setAddress(administrator.getAddress());

		// update
		try {
			adminService.update(persistent);
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}
		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(null);
		return rr;

	}

	/***
	 * 
	 */
	@RequestMapping(value = "/save")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("super-administrator")
	public Object save(HttpServletRequest request, @RequestBody Administrator administrator) {

		ResponseResult rr = new ResponseResult();

		List<QueryCondition> conditions = new ArrayList<QueryCondition>();
		conditions.add(new QueryCondition("phone", QueryCondition.EQ, administrator.getPhone()));
		Administrator oAdministrator = (Administrator) adminService.getSingleResult(Administrator.class, conditions);

		if (oAdministrator != null) {
			rr.setCode(0);
			rr.setInfo("已存在该管理员");
			return rr;
		}

		administrator.setCreateTime(new Date());
		administrator.setActive(true);
		// 随机生成的四位 密码。
		int random = (int) (Math.random() * 10000) + 1000;
		administrator.setPassword(random + "");// default
		// administrator.setSmsCode("smsCode");
		try {
			// save
			adminService.save(administrator);
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}
		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(null);
		return rr;

	}

	/**
	 * 查询 操作人的详细信息
	 * 
	 * @param operatorId
	 * @return
	 * @author Young
	 */
	@RequestMapping(value = "/getOperator")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("super-administrator")
	public Object getOperator(@RequestParam(value = "phone") String operatorId) {
		ResponseResult rr = new ResponseResult();
		Administrator administrator = adminService.getByPhone(operatorId);

		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(administrator);
		return rr;
	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}
}
